// 基本对话框Controller
class DialogController {
  constructor($scope, $mdDialog) {
    $scope.hide = () => {
      $mdDialog.hide();
    };
    $scope.cancel = () => {
      $mdDialog.cancel();
    };
  }
}
// 账户对话框Controller
class SettingsDialogController extends DialogController {
  constructor ($scope, $mdDialog, i18n, settings) {
    super($scope, $mdDialog);
    $scope.save = (updates) => {
      $mdDialog.hide(updates);
    }
    $scope.i18n = i18n;
    console.log(settings)
    $scope.settings = angular.merge({}, settings);
  }
}

// 创建任务Controller
class TaskDialogController extends DialogController {
  constructor ($scope, $mdDialog, i18n, template, task) {
    super($scope, $mdDialog);
    $scope.save = (task) => {
      $mdDialog.hide(task);
    }
    $scope.i18n = i18n;
    if (!task) {
      task = {
        touser: '',
        template_id: template.template_id,
        data: {},
        url: ''
      };
      let str = template.content;
      str.replace(/{{(.*?).DATA}}/g, (g0, g1) => {
        task.data[g1] = {
          value: '',
          color: '#173177'
        }
      });
    }

    $scope.task = task;
  }
}

class MainController {
  constructor($scope, $rootScope, $route, $location, $mdMedia, $mdSidenav, $mdDialog, $mdToast, $i18n, $exception, $wechat, $settings, $task, $queue) {
    this.$mdDialog = $mdDialog;
    this.$mdSidenav = $mdSidenav;
    this.$location = $location;
    this.$wechat = $wechat;
    this.$settings = $settings;
    this.$task = $task;
    this.$queue = $queue;
    this.$i18n = $i18n;
    this.$exception = $exception;
    this.$rootScope = $rootScope;

    this.total = [];
    this.queue = [];
    this.failures = [];
    this.success = [];
    this.unsubscribed = [];

    this.syncing = false;

    $scope.$watch(() => {
      return $mdMedia('xs') || $mdMedia('sm');
    }, (wantsFullScreen) => {
      this.useFullScreen = (wantsFullScreen === true);
    });

    $rootScope.$on('$routeChangeSuccess', () => {
      this.title = this.$i18n[$route.current.title] ? this.$i18n[$route.current.title] : $route.current.title;
      if ($route.current.$$route.controllerAs) {
        this.view = $route.current.$$route.controllerAs;
        this.theme = $route.current.$$route.controllerAs;
      }
      else {
        this.view = '';
        this.theme = '';
      }
    });

    this.$settings.get().then((result) => {
      this.settings = angular.merge({}, result.response);
      console.log(this.settings);
    },
    () => {
      // 设置不存在
      this.showSettings();
    })

    this.$task.get().then((result) => {
      this.task = result.response;
      console.log(result);
      console.log(this.task);
    },
    (error) => {
      console.log(error);
    })

    this.$queue.get().then((result) => {
      this.total = result;
      console.log(result);
      if (result && result.length) {
        result.forEach((item) => {
          if (!item.status) {
            this.queue.push(item);
          }
          else if (item.status === 1) {
            this.success.push(item);
          }
          else if (item.status === 2) {
            this.unsubscribed.push(item);
          }
          else {
            this.failures.push(failures);
          }
        })
      }
    })
  }
  start () {
    if (!this.settings || !this.task) {
      return;
    }
    else if (!this.queue || !this.queue.length) {
      return;
    }
    else if (this.task.state === 'running') {
      return;
    }
    else {
      this.task.state = 'running';
      this.send();
    }
  }
  send () {
    if (this.task.state === 'stopped') {
      return;
    }
    if (!this.queue.length) {
      this.$task.get().then((task) => {
        this.task = task.response;
        if (task.state === 'complete') {
          return;
        }
        this.$task.put(angular.merge({}, this.task, {state: 'complete'})).then(() => {
          // 
        },
        (error) => {
          this.$exception.handle(error)
        })
      },
      (error) => {
      })
      return;
    }
    console.log('send start')
    let current = this.queue.shift();
    let message = angular.merge({}, this.task, {
      'touser': current.openid,
    });
    delete message.created;
    delete message.modified;
    delete message.state;
    console.log(message);
    console.log(this.task)
    this.$wechat.send(message).then(() => {
      this.$queue.put(angular.merge({}, current, {
        status: 1
      })).then(() => {
        this.success.push(current);
        this.send();
      },
      () => {
        this.success.push(current);
        this.send();
      })
    },
    (error) => {
      if (error.errcode) {
        let stopcase = [-1, 40001, 40002, 40003, 40004, 40013, 40014, 40033, 40035, 40038, 40039, 40132, 41001, 42002, 48001];
        let refreshcase = [42001];
        let skipcase = [43004, 46004, 50001, 50002];
        if (stopcase.indexOf(error.errcode) > -1) {
          this.queue.unshift(current);
          this.stop();
          this.$exception.handle(error);
        }
        else if (refreshcase.indexOf(error.errcode) > -1) {
          this.queue.unshift(current);
          this.$wechat.token(true).then(() => {
            this.send();
          },
          (error) => {
            this.$exception.handle(error);
            this.stop();
          })
        }
        else if (skipcase.indexOf(error.errcode) > -1) {
          this.$queue.put(angular.extend({}, current, {
            status: 2
          })).then(() => {
            this.failures.push(current);
            this.send();
          },
          () => {
            this.failures.push(current);
            this.send();
          })
        }
        else {
          this.queue.unshift(current);
          this.stop();
        }
      }
    })
  }
  stop () {
    if (this.task) {
      this.task.state = 'stopped';
    }
  }
  sync () {
    if (this.syncing) {
      return;
    }
    this.syncing = true;
    this.$wechat.templates(true).then((result) => {
      this.$settings.get().then((result) => {
        this.$rootScope.$apply(() => {
          this.syncing = false;
          this.settings = angular.merge({}, result.response);
        })
      },
      (error) => {
        console.log(error);
      })
    },
    (error) => {
      this.$rootScope.$apply(() => {
        this.syncing = false;
      });
    })
  }
  showSettings () {
    this.$mdDialog.show({
      controller: SettingsDialogController,
      templateUrl: '../views/settings.dialog.html',
      parent: angular.element(document.body),
      clickOutsideToClose: true,
      locals: {
        settings: this.settings,
        i18n: this.$i18n
      },
      fullscreen: this.useFullScreen
    })
    .then((settings) => {
      if (settings !== this.settings && Object.keys(settings).length) {
        this.$settings.put(settings).then((result) => {
          console.log(result)
          if (result.status === 200) {
            this.$rootScope.$apply(() => {
              this.settings = settings;
            })
          }
          else {

          }
        },
        (error) => {
          console.log(error);
        });
      }
      console.log(settings);
    }, () => {

    });
  }
  toggleMenu () {
    return this.$mdSidenav('menu')
      .toggle();
  }
  navigateTo (path) {
    this.toggleMenu();
    this.$location.path(path);
  }
  importFollower () {

    chrome.fileSystem.chooseEntry({
      type: 'openWritableFile'
    }, (entry) => {
      entry.file((file) => {
        var reader = new FileReader();
        reader.onerror;
        reader.onload = (e) => {
          let followerlist = JSON.parse(e.target.result);
          this.$queue.delete().then(() => {
            this.$queue.put(followerlist).then((result) => {
              console.log(result);
              this.$queue.get().then((result) => {
                if (result && result.length) {
                  this.total = result;
                  this.queue = [];
                  this.success = [];
                  this.failures = [];
                  this.unsubscribed = [];
                  result.forEach((item) => {
                    if (!item.status) {
                      this.queue.push(item);
                    }
                    else if (item.status === 1) {
                      this.success.push(item);
                    }
                    else if (item.status === 2) {
                      this.unsubscribed.push(item);
                    }
                    else {
                      this.failures.push(failures);
                    }
                  })
                }
              },
              (error) => {
                console.log(e)
              })
            },
            (error) => {
              console.log(error)
            });
          },
          () => {
            console.log('清空数据失败')
          })
        };
        reader.readAsText(file);
      });
    })
  }
}

MainController.$inject = ['$scope', '$rootScope', '$route', '$location', '$mdMedia', '$mdSidenav', '$mdDialog', '$mdToast', '$i18n', '$exception', '$wechat', '$settings', '$task', '$queue'];
angular.module('app').controller('MainController', ['$scope', '$rootScope', '$route', '$location', '$mdMedia', '$mdSidenav', '$mdDialog', '$mdToast', '$i18n', '$exception', '$wechat', '$settings', '$task', '$queue', MainController]);
